<template>
    <div class="defect-item-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="breadcrumb">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>不良品项</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="header-actions">
                <el-button type="primary" @click="handleRefresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-section">
            <el-card shadow="never">
                <el-form :model="searchForm" inline>
                    <el-form-item label="不良品项编号">
                        <el-input v-model="searchForm.defectCode" placeholder="请输入不良品项编号" clearable
                            style="width: 200px" />
                    </el-form-item>
                    <el-form-item label="不良品项名称">
                        <el-input v-model="searchForm.defectName" placeholder="请输入不良品项名称" clearable
                            style="width: 200px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <el-icon>
                                <Search />
                            </el-icon>
                            查询
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-section">
            <el-button type="success" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>
                新建
            </el-button>
            <el-button type="primary" @click="handleEdit" :disabled="!hasSelection">
                <el-icon>
                    <Edit />
                </el-icon>
                编辑
            </el-button>
            <!-- <el-button type="danger" @click="handleDelete" :disabled="!hasSelection">
                <el-icon>
                    <Delete />
                </el-icon>
                删除
            </el-button>
            <el-button type="success" @click="handleImport">
                <el-icon>
                    <Upload />
                </el-icon>
                导入
            </el-button>
            <el-button type="success" @click="handleExport">
                <el-icon>
                    <Download />
                </el-icon>
                导出
            </el-button> -->
            <!-- <el-button @click="handleColumnSettings">
                <el-icon>
                    <Setting />
                </el-icon>
                列设置
            </el-button> -->
        </div>

        <!-- 数据表格 -->
        <div class="table-section">
            <el-card shadow="never">
                <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" stripe border
                    style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" label="序号" width="60" />
                    <el-table-column prop="defectCode" label="不良品项编号" min-width="180" sortable />
                    <el-table-column prop="defectName" label="不良品项名称" min-width="150" sortable />
                    <el-table-column prop="attachmentUrl" label="附件" width="100">
                        <template #default="{ row }">
                            <el-link v-if="row.attachmentUrl" type="primary" @click="handleViewAttachment(row)">
                                查看附件
                            </el-link>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="imageUrl" label="图片" width="100">
                        <template #default="{ row }">
                            <el-image v-if="row.imageUrl" :src="getImageUrl(row.imageUrl)"
                                :preview-src-list="[getImageUrl(row.imageUrl)]" fit="cover"
                                style="width: 40px; height: 40px">
                                <template #error>
                                    <div class="image-placeholder">图片</div>
                                </template>
                            </el-image>
                            <div v-else class="image-placeholder">图片</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180" sortable>
                        <template #default="{ row }">
                            {{ formatDateTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="creator" label="创建人" width="120" />
                    <el-table-column prop="modifier" label="修改人" width="120" />
                    <el-table-column prop="modifyTime" label="修改时间" width="180" sortable>
                        <template #default="{ row }">
                            {{ formatDateTime(row.modifyTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="testField" label="测试字段" width="100" />
                </el-table>

                <!-- 分页 -->
                <div class="pagination-section">
                    <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 30, 50]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 新建/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="不良品项编号" prop="defectCode">
                    <el-input v-model="form.defectCode" placeholder="请输入不良品项编号" :disabled="!!form.defectItemId" />
                    <div class="form-tip" v-if="!form.defectItemId">
                        <el-button type="text" size="small" @click="regenerateCode"
                            style="padding: 0; margin-right: 8px;">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            重新生成
                        </el-button>
                        编号格式：BL + 年月日时分秒 + 3位随机数
                    </div>
                </el-form-item>
                <el-form-item label="不良品项名称" prop="defectName">
                    <el-input v-model="form.defectName" placeholder="请输入不良品项名称" />
                </el-form-item>
                <el-form-item label="附件">
                    <div class="upload-section">
                        <el-upload class="upload-demo" action="#" :auto-upload="false" :on-change="handleFileChange"
                            :file-list="fileList" :on-remove="handleFileRemove">
                            <el-button type="primary">选择文件</el-button>
                        </el-upload>
                        <div class="upload-tip">支持的文件格式：PDF、DOC、DOCX、XLS、XLSX等，文件大小不超过50MB</div>
                    </div>
                </el-form-item>
                <el-form-item label="图片">
                    <div class="image-upload-section">
                        <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false"
                            :on-change="handleImageChange" accept="image/*">
                            <img v-if="form.imageUrl" :src="getImageUrl(form.imageUrl)" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <div class="upload-tip">支持JPG、PNG、GIF等格式，文件大小不超过10MB</div>
                    </div>
                </el-form-item>
                <el-divider content-position="left">
                    <span class="divider-title">扩展字段</span>
                </el-divider>
                <el-form-item label="测试字段" prop="testField">
                    <el-input v-model="form.testField" placeholder="请输入测试字段" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        <el-icon v-if="!submitLoading">
                            <Check />
                        </el-icon>
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Upload,
    Download,
    Setting,
    Check
} from '@element-plus/icons-vue'
import { MES_XSP_ApiHost } from '@/utils/Interceptors'
import moment from 'moment'

// 接口定义
interface DefectItem {
    defectItemId: number
    defectCode: string
    defectName: string
    testField?: string
    attachmentUrl?: string
    imageUrl?: string
    createTime?: string
    creator?: string
    modifyTime?: string
    modifier?: string
    isDelete: boolean
}

interface SearchForm {
    defectCode?: string
    defectName?: string
}

interface Pagination {
    pageIndex: number
    pageSize: number
    total: number
}

interface ApiResponse<T> {
    code: number
    msg: string
    data: T
}

interface ApiPagingResponse<T> {
    code: number
    msg: string
    data: T[]
    totalCount: number
    totalPage: number
    pageData: T[]
}

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<DefectItem[]>([])
const selectedRows = ref<DefectItem[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const fileList = ref<any[]>([])

// 搜索表单
const searchForm = reactive<SearchForm>({
    defectCode: '',
    defectName: ''
})

// 分页信息
const pagination = reactive<Pagination>({
    pageIndex: 1,
    pageSize: 30,
    total: 0
})

// 表单数据
const form = reactive<DefectItem>({
    defectItemId: 0,
    defectCode: '',
    defectName: '',
    testField: '',
    attachmentUrl: '',
    imageUrl: '',
    createTime: '',
    creator: '',
    modifyTime: '',
    modifier: '',
    isDelete: false
})

// 表单验证规则
const rules = {
    defectName: [
        { required: true, message: '请输入不良品项名称', trigger: 'blur' }
    ]
}

// 计算属性
const hasSelection = computed(() => selectedRows.value.length > 0)

// 获取数据列表
const fetchData = async () => {
    loading.value = true
    try {
        const params = {
            ...searchForm,
            pageIndex: pagination.pageIndex,
            pageSize: pagination.pageSize
        }

        const response = await MES_XSP_ApiHost.get('/api/DefectItem/GetDefectItemList', { params })

        if (response.data.code === 200) {
            tableData.value = response.data.pageData || []
            pagination.total = response.data.totalCount || 0
        } else {
            ElMessage.error(response.data.msg || '获取数据失败')
        }
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败，请检查网络连接')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.pageIndex = 1
    fetchData()
}

// 重置搜索
const handleReset = () => {
    Object.assign(searchForm, {
        defectCode: '',
        defectName: ''
    })
    pagination.pageIndex = 1
    fetchData()
}

// 刷新
const handleRefresh = () => {
    fetchData()
}

// 表格选择变化
const handleSelectionChange = (rows: DefectItem[]) => {
    selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.pageIndex = 1
    fetchData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
    pagination.pageIndex = page
    fetchData()
}

// 新建
const handleAdd = () => {
    dialogTitle.value = '新建不良品项'
    resetForm()
    // 自动生成编号
    form.defectCode = generateDefectCode()
    dialogVisible.value = true
}

// 编辑
const handleEdit = () => {
    if (selectedRows.value.length !== 1) {
        ElMessage.warning('请选择一条记录进行编辑')
        return
    }
    const row = selectedRows.value[0]
    editRow(row)
}

// 编辑单行
const handleEditRow = (row: DefectItem) => {
    editRow(row)
}

// 编辑行数据
const editRow = (row: DefectItem) => {
    dialogTitle.value = '编辑不良品项'
    Object.assign(form, row)

    // 设置文件列表
    if (row.attachmentUrl) {
        fileList.value = [{
            name: '附件',
            url: row.attachmentUrl
        }]
    } else {
        fileList.value = []
    }

    dialogVisible.value = true
}

// 删除
const handleDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 条记录吗？此操作不可恢复！`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true
            }
        )

        // 批量删除
        const ids = selectedRows.value.map(row => row.defectItemId)
        const response = await MES_XSP_ApiHost.delete('/api/DefectItem/BatchDeleteDefectItem', {
            data: ids
        })

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || '删除成功')
            selectedRows.value = []
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }
}

// 删除单行
const handleDeleteRow = async (row: DefectItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除不良品项"${row.defectName}"吗？此操作不可恢复！`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true
            }
        )

        const response = await MES_XSP_ApiHost.delete(`/api/DefectItem/DeleteDefectItem/${row.defectItemId}`)

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || '删除成功')
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }
}

// 导入
const handleImport = () => {
    ElNotification({
        title: '提示',
        message: '导入功能待实现',
        type: 'info'
    })
}

// 导出
const handleExport = () => {
    ElNotification({
        title: '提示',
        message: '导出功能待实现',
        type: 'info'
    })
}

// 列设置
const handleColumnSettings = () => {
    ElNotification({
        title: '提示',
        message: '列设置功能待实现',
        type: 'info'
    })
}

// 获取图片完整URL
const getImageUrl = (imageUrl: string): string => {
    if (!imageUrl) return ''

    // 如果已经是完整URL，直接返回
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return imageUrl
    }

    // 如果是相对路径，拼接后端API基础路径
    const baseUrl = 'http://localhost:5058' // MES_XSP_ApiHost的baseURL
    const fullUrl = `${baseUrl}${imageUrl}`

    // 调试输出
    console.log('Image URL:', imageUrl, 'Full URL:', fullUrl)

    return fullUrl
}

// 查看附件
const handleViewAttachment = (row: DefectItem) => {
    if (row.attachmentUrl) {
        const attachmentUrl = getImageUrl(row.attachmentUrl)
        window.open(attachmentUrl, '_blank')
    }
}

// 文件变化
const handleFileChange = async (file: any) => {
    try {
        // 验证文件大小
        if (file.raw.size > 50 * 1024 * 1024) {
            ElMessage.error('文件大小不能超过50MB')
            return
        }

        const formData = new FormData()
        formData.append('file', file.raw)

        const response = await MES_XSP_ApiHost.post('/api/FileUpload/UploadFile', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        if (response.data.code === 200) {
            form.attachmentUrl = response.data.data
            ElMessage.success('附件上传成功')
        } else {
            ElMessage.error(response.data.msg || '附件上传失败')
        }
    } catch (error) {
        console.error('附件上传失败:', error)
        ElMessage.error('附件上传失败')
    }
}

// 文件移除
const handleFileRemove = () => {
    form.attachmentUrl = ''
    fileList.value = []
}

// 图片变化
const handleImageChange = async (file: any) => {
    try {
        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']
        if (!allowedTypes.includes(file.raw.type)) {
            ElMessage.error('只支持上传图片文件（JPG、PNG、GIF、BMP、WebP）')
            return
        }

        // 验证文件大小
        if (file.raw.size > 10 * 1024 * 1024) {
            ElMessage.error('图片文件大小不能超过10MB')
            return
        }

        const formData = new FormData()
        formData.append('file', file.raw)

        const response = await MES_XSP_ApiHost.post('/api/FileUpload/UploadImage', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        if (response.data.code === 200) {
            form.imageUrl = response.data.data
            ElMessage.success('图片上传成功')
        } else {
            ElMessage.error(response.data.msg || '图片上传失败')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        ElMessage.error('图片上传失败')
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        // 如果是新增且编号为空，自动生成编号
        if (!form.defectItemId && !form.defectCode) {
            form.defectCode = generateDefectCode()
        }

        const submitData = {
            defectItemId: form.defectItemId || null,
            defectCode: form.defectCode || '',
            defectName: form.defectName,
            testField: form.testField,
            attachmentUrl: form.attachmentUrl,
            imageUrl: form.imageUrl,
            creator: 'Admin' // 这里应该从用户上下文获取
        }

        let response
        if (form.defectItemId) {
            // 编辑
            response = await MES_XSP_ApiHost.put('/api/DefectItem/UpdateDefectItem', submitData)
        } else {
            // 新增
            response = await MES_XSP_ApiHost.post('/api/DefectItem/AddDefectItem', submitData)
        }

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || (form.defectItemId ? '更新成功' : '创建成功'))
            dialogVisible.value = false
            fetchData()
        } else {
            ElMessage.error(response.data.msg || '操作失败')
        }
    } catch (error) {
        console.error('表单提交失败:', error)
        ElMessage.error('操作失败，请稍后重试')
    } finally {
        submitLoading.value = false
    }
}

// 对话框关闭
const handleDialogClose = () => {
    resetForm()
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        defectItemId: 0,
        defectCode: '',
        defectName: '',
        testField: '',
        attachmentUrl: '',
        imageUrl: '',
        createTime: '',
        creator: '',
        modifyTime: '',
        modifier: '',
        isDelete: false
    })

    fileList.value = []

    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 生成不良品项编号
const generateDefectCode = (): string => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')

    // 生成3位随机数
    const randomNum = Math.floor(Math.random() * 900) + 100 // 100-999

    return `BL${year}${month}${day}${hour}${minute}${second}${randomNum}`
}

// 重新生成编号
const regenerateCode = () => {
    if (!form.defectItemId) {
        form.defectCode = generateDefectCode()
        ElMessage.success('编号已重新生成')
    }
}

// 格式化日期时间
const formatDateTime = (dateTime: string | undefined) => {
    if (!dateTime) return '-'
    return moment(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 页面加载时获取数据
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.defect-item-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-section {
    margin-bottom: 20px;
}

.action-section {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.table-section {
    margin-bottom: 20px;
}

.pagination-section {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.image-placeholder {
    width: 40px;
    height: 40px;
    background-color: #f0f0f0;
    border: 1px solid #d9d9d9;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #999;
}

.avatar-uploader {
    text-align: center;
}

.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    border-radius: 6px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.upload-section,
.image-upload-section {
    width: 100%;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    line-height: 1.4;
}

.divider-title {
    font-weight: 500;
    color: #409eff;
}
</style>
